<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="68px"
      @submit.native.prevent
    >
      <el-form-item label="数据表名" prop="tableName">
        <el-input
          v-model.trim="queryParams.tableName"
          placeholder="请输入数据表名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >清除所有过滤器</el-button
        >
      </el-form-item>
      <el-form-item>
        <timeSearch
          @getDateArr="getDateArr"
          @changDay="changDay"
          :timeArr="timeArr"
          :dayActive="this.dayActive"
          :dayLimit="1095"
        />
      </el-form-item>
    </el-form>
    <div style="display: flex; justify-content: space-between">
      <el-row :gutter="10" class="mb8" style="width: 85%">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="opentagkey"
            >增加</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            >修改</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            >删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            >导出</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            size="mini"
            plain
            icon="el-icon-upload"
            @click="daoru"
            >批量导入</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button size="mini" @click="handlePosition">调整表头</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button size="mini" @click="handleRuleTagger">打标</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button size="mini" @click="handlesysData">同步</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button size="mini" @click="handleBiruletag">配置标签</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button size="mini" @click="handleBiTableRelation"
            >配置BI关系表</el-button
          >
        </el-col>
        <!-- <el-col :span="1.5">
        <el-button
          icon="el-icon-more"
          size="mini"
          circle
          @click="colsVisible = true"
        ></el-button>
      </el-col> -->
        <!-- <el-col :span="1.5">
        <el-popover width="60" trigger="click">
          <el-checkbox-group v-model="columnSelecteds">
            <el-checkbox
              v-for="item in cols"
              :label="item.title"
              :key="item.title"
            ></el-checkbox>
          </el-checkbox-group>

          <el-button
            slot="reference"
            icon="el-icon-more"
            size="mini"
            circle
          ></el-button>
        </el-popover>
      </el-col> -->

        <el-col :span="1.5" :key="tag.key" v-for="tag in entriesObjectsArray">
          <el-tag
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ getTagNameComment(tag.key) }}
            {{ tag.value.operator }}{{ tag.value.value }}
          </el-tag>
        </el-col>

        <!-- <right-toolbar @queryTable="getList" :columns="cols"></right-toolbar> -->
      </el-row>
      <span style="color: #606266; margin-right: 5px">
        {{ javaUpdateTime ? "更新时间:" + javaUpdateTime : "" }}
      </span>
    </div>
    <el-table
      class="tb-edit"
      highlight-current-row
      :data="tableData"
      border
      style="width: 100%"
      :height="600"
      @sort-change="handleSortChange"
      ref="table"
      @row-dblclick="t"
      row-key="id"
      @selection-change="handleSelectionChange"
    >
      <!-- v-if="col.field_name.toLowerCase().includes('url'.toLowerCase())" -->
      <el-table-column type="selection" width="55" align="center" />
      <template>
        <!-- <el-table-column
          :key="col.field_name"
          :prop="col.field_name"
          align="center"
          width="100"
          sortable
        >
          <template v-slot:header>
            <span>{{ col.comment }} </span>
          </template>
          <template slot-scope="scope">
            <image-preview
              :src="scope.row.pic_url"
              :width="40"
              :height="40"
            /> </template
        ></el-table-column>


        :prop="cols[index].field_name"

      :visible="columns[index].visible"
      v-if="cols[index].isShow"
      -->

        <el-table-column
          v-for="(col, index) in cols"
          :key="col.id"
          :prop="cols[index].field_name"
          :label="col.comment"
          align="center"
          width="160"
          sortable
        >
          <template v-slot:header>
            <span>{{ cols[index].comment }} </span>

            <FilterInput
              :fieldName="cols[index].field_name"
              :tableName="queryParams.tableName"
              :person="person"
              @filterChange="handleFilterChange($event, cols[index].field_name)"
            />
          </template>
          <template slot-scope="scope">
            <image-preview
              v-if="
                String(scope.row[cols[index].field_name]).includes('profile')
              "
              :src="scope.row[cols[index].field_name]"
              :width="30"
              :height="30"
            />
            <span v-else>
              {{ scope.row[cols[index].field_name] }}
            </span>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <el-dialog
      :visible.sync="tagkeyVisible"
      width="500px"
      append-to-body
      v-if="tagkeyVisible"
    >
      <div class="el-dialog-div">
        <el-form
          ref="form"
          :model="formData"
          label-position="top"
          :inline="true"
        >
          <el-form-item
            v-for="(item, index) in formData.libraryIdList"
            :key="index"
          >
            <el-input
              :disabled="true"
              style="width: 150px"
              v-model="item.comment"
              placeholder="请输入字段名"
            ></el-input>
            <!-- <el-input
              style="width: 150px"
              v-model="item.field_name"
              placeholder="请输入字段值"
            ></el-input> -->
            <el-input
              style="width: 150px"
              v-model="item.value"
              placeholder="请输入字段值"
            ></el-input>
            <span v-if="item.is_nullable == 'NO'">(必填)</span>
            <!-- <span v-if="formData.libraryIdList.length > 1">
              <el-button type="primary" size="mini" @click="addLibraryIdList"
                >新增</el-button
              >
              <el-button type="danger" size="mini" @click="delRow(item, index)"
                >删除</el-button
              >
            </span> -->
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改产品二级信息对话框 :on-change="handleChange"-->
    <el-dialog
      title="导入"
      :visible.sync="dialogVisible"
      width="500px"
      append-to-body
      v-if="dialogVisible"
    >
      <!-- 文件上传-->
      <el-form
        :model="dataForm"
        ref="dataForm"
        label-width="80px"
        @submit.native.prevent
        :inline="true"
        ><el-row>
          <el-form-item label="是否校验">
            <el-checkbox true-label="0" false-label="1" v-model="isCheckDataNum"
              >是否校验数据条数</el-checkbox
            >
          </el-form-item>
        </el-row>
        <el-form-item label="文件：" prop="file" :inline="true">
          <el-row>
            <el-upload
              class="upload-import"
              ref="uploadImport"
              :http-request="httpRequest"
              action=""
              :on-remove="handleRemove"
              :file-list="fileList"
              :limit="1"
              :on-change="handleChange"
              :auto-upload="false"
              :before-upload="beforeAvatarUpload"
            >
              <!--
            accept="application/zip,.zip" 设置接收的文件类型-->
              <el-button
                v-show="!hasFile"
                slot="trigger"
                size="small"
                type="primary"
                >选取文件</el-button
              >
              <!-- <div slot="tip" class="el-upload__tip">
          只能上传zip文件，且不超过10M
        </div> -->
            </el-upload>
            <!-- 关闭自动上传-->
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="addLibraryIdList"
              >新增抬头</el-button
            >
          </el-row>
        </el-form-item>

        <div
          class="el-dialog-divupload"
          v-if="formData.libraryIdList.length > 0"
        >
          <el-form-item
            v-for="(item, index) in formData.libraryIdList"
            :key="index"
          >
            <!-- <el-input
              
              style="width: 150px"
              v-model="item.comment"
              placeholder="请输入字段名"
            ></el-input> -->
            <el-select
              style="width: 150px"
              v-model="item.field_name"
              placeholder="请输入字段"
              clearable
              filterable
              allow-create
              @change="changefieldName(item)"
            >
              <el-option
                v-for="dict in tableNameList"
                :key="dict.field_name"
                :label="dict.comment"
                :value="dict.field_name"
              />
            </el-select>
            <el-input
              style="width: 150px"
              v-model="item.value"
              placeholder="请输入字段值"
            ></el-input>
            <span v-if="formData.libraryIdList.length > 0">
              <el-button type="danger" size="mini" @click="delRow(item, index)"
                >删除</el-button
              >
            </span>
          </el-form-item>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpload">提交</el-button>
        <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      @close="Closedatacols"
      :visible.sync="colsVisible"
      width="800px"
      append-to-body
    >
      <datacols :tableName="queryParams.tableName" />
    </el-dialog>
    <el-dialog
      :visible.sync="opencols"
      width="800px"
      append-to-body
      @close="Closedatacols"
    >
      <cols
        :tableName="queryParams.tableName"
        :countCols="countCols"
        @close="Closecols"
      />
    </el-dialog>

    <el-dialog
      :visible.sync="openForBiruletag"
      width="1500px"
      append-to-body
      v-if="openForBiruletag"
    >
      <component :is="'Biruletag'" :sqlTableName="sqlTableName"></component>
    </el-dialog>
    <el-dialog
      :visible.sync="openBiTableRelation"
      width="1500px"
      append-to-body
      v-if="openBiTableRelation"
    >
      <component
        :is="'BiTableRelationshipConfig'"
        :tableName="sqlTableName"
      ></component>
    </el-dialog>
  </div>
</template>  
  
<script>
import Sortable from "sortablejs";
import Biruletag from "@/views/conf/biruletag/Biruletag.vue";
import BiTableRelationshipConfig from "@/views/conf/BiTableRelationshipConfig/index.vue";
import { listSysTableData } from "@/api/conf/SysTableData";
import axios from "axios";
//--------导入token
import { getToken } from "@/utils/auth";
import FilterInput from "./FilterInput.vue";
import datacols from "./datacols.vue";
import cols from "./cols.vue";
// import { bitableoperation } from "@/api/conf/BiRuleSpecifications";
import {
  deleteoperation,
  bitableoperation,
  sysData,
  getUpdateTime,
} from "@/api/conf/bitableoperation";

import {
  RuleTagger,
  getTablefieldsWithComments,
} from "@/api/conf/BiRuleSpecifications";
import timeSearch from "@/common/day";
export default {
  components: {
    Biruletag,
    FilterInput,
    datacols,
    cols,
    timeSearch,
    BiTableRelationshipConfig,
  },
  // props: {
  //   tableName: {
  //     type: String,
  //     default: "",
  //   },
  // },
  data() {
    return {
      isCheckDataNum: "1",
      openBiTableRelation: false,
      openForBiruletag: false,
      sqlTableName: "",
      //更新时间:年月日 时分秒
      javaUpdateTime: "2025-01-10 11:16:04",
      //每次打开弹窗刷新页面
      countCols: 0,
      tableNameList: [],
      dayActive: 30,
      timeArr: [
        // { value: "2", label: "昨天" },
        // { value: "7", label: "最近7天" },
        { value: "30", label: "最近30天" },
        { value: "365", label: "最近一年" },
        { value: "1", label: "日" },
      ],
      timeGap: { startTime: "", endTime: "" },
      opencols: false,
      // 遮罩层
      loading: true,
      colsVisible: false,
      // 列信息
      columnSelecteds: [],
      isEdit: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,

      hasFile: false,
      fileList: [],
      dialogVisible: false,
      pjtUrl: process.env.VUE_APP_BASE_API,
      dataForm: {
        file: null,
      },

      tagkeyVisible: false,
      formData: {
        libraryIdList: [],
      },
      //动态参数
      entriesObjectsArray: [],
      // 查询参数
      queryParams: {
        page: 1,
        size: 10,

        tableName: "bi_rule_specifications",
      },
      person: {},

      cols: [],
      tableData: [],
      total: 0,
    };
  },
  created() {
    var route = JSON.parse(localStorage.getItem("route"));
    console.log(JSON.stringify(route));
    let parts = route.split("/");
    let lastPart = parts[parts.length - 1];
    console.log(lastPart);
    listSysTableData({ tableName: lastPart }).then((response) => {
      if (response.rows.length > 0) {
        this.queryParams.tableName = lastPart;
      }
      // else {
      //   this.queryParams.tableName = this.tableName;
      // }

      this.getList();
    });
  },
  beforeDestroy() {
    this.$emit("deleteAll");
  },
  // updated() {
  //   this.columnDrop();
  // },
  watch: {
    // tableName: {
    //   handler: function (newnew, oldold) {
    //     if (!this.tableName) {
    //       this.queryParams.tableName = this.tableName;
    //       this.getList();
    //     }
    //   },
    //   deep: true,
    //   immediate: true,
    // },
    // 监听复选框配置列所有的变化
    // cols: {
    //   handler: function (newnew, oldold) {
    //     this.openLoading();
    //     // this.cols = newnew;
    //     this.$nextTick(() => {
    //       this.$refs["table"].doLayout();
    //       this.$modal.closeLoading();
    //       // this.columnDrop();
    //     });
    //   },
    //   deep: true,
    //   immediate: true,
    // },
    /**
     * @title 监听列显示隐藏
     */
    // columnSelecteds(newArrayVal) {
    //   // 计算为被选中的列标题数组
    //   var nonSelecteds = this.cols
    //     .filter((item) => newArrayVal.indexOf(item.title) == -1)
    //     .map((item) => item.title); // 根据计算结果进行表格重绘
    //   this.cols.filter((item) => {
    //     let isNonSelected = nonSelecteds.indexOf(item.title) != -1;
    //     if (isNonSelected) {
    //       // 隐藏未选中的列
    //       item.isShow = false;
    //       this.$nextTick(() => {
    //         this.$refs.table.doLayout();
    //       });
    //     } else {
    //       // 显示已选中的列
    //       item.isShow = true;
    //       this.$nextTick(() => {
    //         this.$refs.table.doLayout();
    //       });
    //     }
    //   });
    // },
  },
  // #app > div.app-wrapper.openSidebar > div.main-container.hasTagsView > div > div.el-scrollbar__wrap > div > section > div > div.el-table.tb-edit.el-table--fit.el-table--border.el-table--scrollable-x.el-table--enable-row-hover.el-table--enable-row-transition.el-table--medium > div.el-table__header-wrapper > table > thead > tr
  methods: {
    //时间控件
    changDay(val) {
      this.dayActive = val;
      this.timeGap.startTime = val[0];
      this.timeGap.endTime = val[1];
    },
    getDateArr(value) {
      this.timeGap.startTime = value[0];
      this.timeGap.endTime = value[1];
      console.log(JSON.stringify(this.timeGap));
      this.dayActive = 1;
    },
    handlesysData() {
      let obj = {
        tableName: this.queryParams.tableName,
        startDate: this.timeGap.startTime,
        endDate: this.timeGap.endTime,
      };
      this.openLoading();
      sysData(obj).then((response) => {
        this.$modal.closeLoading();
        if (response.code == 200) {
          this.$modal.msgSuccess("同步成功");
        }
      });
    },
    Closecols() {
      this.opencols = false;
    },
    //关闭列的显示与隐藏
    Closedatacols() {
      this.getList();
    },
    getList() {
      // if (!this.queryParams.tableName) {
      //   this.$message.warning("请输入表名");
      //   return;
      // }
      let obj = {
        params: this.queryParams,
        data: this.person,
      };

      this.openLoading();

      bitableoperation(obj).then((response) => {
        this.$modal.closeLoading();
        // if (response.data.cols.length > 0) {
        //   response.data.cols.forEach((item, i) => {
        //     item.isShow = true;
        //     item.title = item.comment;
        //     item.key = i;
        //   });
        // }
        // this.columnSelecteds = response.data.cols.map((item) => item.title);

        this.tableData = response.data.tableData ? response.data.tableData : [];
        this.total = response.data.total ? response.data.total : 0;
        this.cols = [];
        this.cols = response.data.cols ? response.data.cols : [];

        for (let index in this.cols) {
          this.cols[index].id = parseInt(index);
        }
        this.$nextTick(() => {
          this.$refs["table"].doLayout();
        });
        //   this.columnDrop();
        // this.$modal.closeLoading();

        // this.$refs["table"].doLayout();
        // this.cols = [];
      });
      //更新时间:年月日 时分秒
      getUpdateTime({ tableName: this.queryParams.tableName }).then(
        (response) => {
          this.javaUpdateTime = response;
        }
      );
    },
    // columnDrop() {
    //   // const dropCol = this.cols;
    //   //获取dom节点
    //   const wrapperTr = this.$refs.table.$el.querySelectorAll(
    //     ".el-table__header-wrapper > table > thead > tr"
    //   )[0];
    //   Sortable.create(wrapperTr, {
    //     animation: 180,
    //     delay: 0,
    //     onEnd: (evt) => {
    //       const oldItem = this.cols[evt.oldIndex];
    //       this.cols.splice(evt.oldIndex, 1);
    //       this.cols.splice(evt.newIndex, 0, oldItem);
    //     },
    //   });

    //   // return dropCol;
    // },
    columnDrop() {
      // const dropCol = this.cols;
      //获取dom节点
      const wrapperTr = this.$refs.table.$el.querySelectorAll(
        ".el-table__header-wrapper > table > thead > tr"
      )[0];
      Sortable.create(wrapperTr, {
        animation: 180,
        delay: 0,
        onEnd: (evt) => {
          const oldItem = this.cols[evt.oldIndex - 1];
          this.cols.splice(evt.oldIndex - 1, 1);
          this.cols.splice(evt.newIndex - 1, 0, oldItem);
          // for (let index in this.cols) {
          //   this.cols[index].sort = parseInt(index) + 1;
          // }
        },
      });

      // return dropCol;
    },
    handleUpdate() {
      let obj = {
        params: this.queryParams,
        data: {
          id: [{ operator: "=", value: this.ids[0] }],
        },
      };
      // this.openLoading();
      bitableoperation(obj).then((response) => {
        this.cols = response.data.cols;
        this.t(response.data.tableData[0]);
        // this.$modal.closeLoading();
        // this.cols = response.cols ? response.cols : [];
        // this.tableData = response.tableData ? response.tableData : [];
      });
    },
    //点击某一行
    t(row, column, cell, event) {
      this.ids = [row.id];
      // console.log(row, column, cell, event);
      // console.log(JSON.stringify(column));
      // this.handleUpdate(row);
      //
      let arr = Object.entries(row).map(([key, value]) => ({ key, value }));
      console.log(JSON.stringify(arr));
      let list = [];

      arr.forEach((item) => {
        if (item.key != "id" && item.key != "field_name") {
          list.push({
            comment: this.getTagNameComment(item.key),
            field_name: item.key,
            value: item.value,
            is_nullable: this.getTagNamenullable(item.key),
          });
        }
      });

      this.formData.libraryIdList = list;
      this.tagkeyVisible = true;
      this.isEdit = true;
    },
    handlePosition() {
      this.countCols++;
      this.opencols = true;
      return;
      this.handleadjustFieldPosition();
    },

    handleadjustFieldPosition() {
      let fd = [...this.cols];
      // fd.tableTotal = this.cols.map((item) => {
      //   item.field_name, item.comment;
      // });
      axios
        .put(
          process.env.VUE_APP_BASE_API +
            "/conf/bitableoperation/adjustFieldPosition?tableName=" +
            this.queryParams.tableName,
          fd,
          {
            headers: {
              header: {
                // responseType: "blob"
              },

              Authorization: "Bearer " + getToken(),
              // "Content-Type": "multipart/form-data",
            }, //定义内容格式,很重要
            // timeout: 20000,
          }
        )
        .then((response) => {
          if (response.data.code == 200) {
            this.$modal.msgSuccess("调整成功");
          } else {
            this.$modal.msgError("调整失败");
          }
        });
    },
    /** 提交按钮 */
    submitForm() {
      let fd = {};
      this.formData.libraryIdList.forEach((item) => {
        // if (item.value != "") {
        fd[item.field_name] = item.value;
        // }
      });
      if (this.isEdit == false) {
        axios
          .post(
            process.env.VUE_APP_BASE_API +
              "/conf/bitableoperation/insert?tableName=" +
              this.queryParams.tableName,
            fd,
            {
              headers: {
                header: {
                  // responseType: "blob"
                },

                Authorization: "Bearer " + getToken(),
                // "Content-Type": "multipart/form-data",
              }, //定义内容格式,很重要
              // timeout: 20000,
            }
          )
          .then((response) => {
            if (response.data.code == 200) {
              this.tagkeyVisible = false;
              this.getList();
              this.$modal.msgSuccess("增加成功");
            } else {
              this.$modal.msgError("增加失败");
            }
          });
      } else if (this.isEdit == true) {
        axios
          .put(
            process.env.VUE_APP_BASE_API +
              "/conf/bitableoperation/update?tableName=" +
              this.queryParams.tableName +
              "&idColumn=id&idValue=" +
              this.ids[0],
            fd,
            {
              headers: {
                header: {
                  // responseType: "blob"
                },

                Authorization: "Bearer " + getToken(),
                // "Content-Type": "multipart/form-data",
              }, //定义内容格式,很重要
              // timeout: 20000,
            }
          )
          .then((response) => {
            if (response.data.code == 200) {
              this.isEdit = false;
              this.tagkeyVisible = false;
              this.$modal.msgSuccess("修改成功");
              this.getList();
            } else {
              this.$modal.msgError("修改失败");
            }
          });
      }
    },
    opentagkey() {
      let list = [];
      this.cols.forEach((item) => {
        if (item.field_name != "id") {
          list.push({ ...item, value: null });
        }
      });
      this.formData.libraryIdList = list;
      this.tagkeyVisible = true;
      this.isEdit = false;
    },

    // 取消按钮
    cancel() {
      this.tagkeyVisible = false;
    },
    //添加库存名称
    addLibraryIdList() {
      this.formData.libraryIdList.push({
        comment: "",
        field_name: "",
        value: "",
      });
    },
    //库存名称删除
    delRow(item, index) {
      if (this.formData.libraryIdList.length > 0) {
        this.formData.libraryIdList.splice(index, 1);
      }
      // else {
      //   this.$message.warning("至少选择一项");
      // }
    },

    handleSortChange(column) {
      /**
  排序方向 asc 升序 desc 降序
 
private String orderDirection;*/
      switch (column.order) {
        case "ascending":
          this.queryParams.sortDirection = "asc";
          break;
        case "descending":
          this.queryParams.sortDirection = "desc";
          break;
        default:
          this.queryParams.sortDirection = null;
          break;
      }
      this.queryParams.orderBy = column.prop; //查询字段是表格中字段名字
      // this.queryParams.orderDirection = column.order;//动态取值排序顺序
      this.getList();
    },
    handleFilterChange(event, filterType) {
      this.person[filterType] = event;
      console.log(JSON.stringify(this.person));
      this.getList();
      // this.entriesObjectsArray = Object.entries(this.person).map(
      //   ([key, value]) => ({ key, value })
      // );
      // console.log(JSON.stringify(this.entriesObjectsArray));
      this.entriesObjectsArray = [];
      // 遍历每个键（tag_id和tag_name）
      for (const key in this.person) {
        if (this.person.hasOwnProperty(key)) {
          // 遍历每个键对应的数组
          for (const item of this.person[key]) {
            // 为每个数组元素创建一个新对象，并添加到transformedArray中
            this.entriesObjectsArray.push({
              key: key, // 设置key属性的值为当前遍历的键名
              value: item, // 设置value属性的值为当前遍历的数组元素
            });
          }
        }
      }
    },
    //关闭条件
    handleClose(tag) {
      var index = this.entriesObjectsArray.indexOf(tag);
      this.entriesObjectsArray.splice(index, 1);
      console.log(JSON.stringify(this.entriesObjectsArray));
      this.person = {};
      this.person = this.entriesObjectsArray.reduce((acc, item) => {
        // 如果累加器对象（acc）中还没有当前key，则初始化为一个空数组
        if (!acc[item.key]) {
          acc[item.key] = [];
        }
        // 将当前item的value添加到对应key的数组中
        acc[item.key].push(item.value);
        // 返回累加器对象以供下一次迭代使用
        return acc;
      }, {});
      // this.entriesObjectsArray.forEach((item) => {
      //   this.person[item.key] = item.value;
      // });
      console.log(JSON.stringify(this.person));
      this.getList();
    },
    getTagNameComment(tagName) {
      const item = this.cols.find((col) => col.field_name === tagName);
      return item ? item.comment : "";
    },
    getTagNamenullable(tagName) {
      const item = this.cols.find((col) => col.field_name === tagName);
      return item ? item.is_nullable : "";
    },

    handleQuery() {
      this.queryParams.page = 1;
      setTimeout(this.getList(), 500);
    },
    resetQuery() {
      this.entriesObjectsArray = [];
      this.person = {};
      this.queryParams.sortDirection = null;
      this.queryParams.orderBy = null;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      console.log(JSON.stringify(ids));
      let obj = {
        tableName: this.queryParams.tableName,
        idColumn: "id",
        idValue: ids[0],
      };

      this.$modal
        .confirm('是否确认删除编号为"' + ids + '"的数据项？')
        .then(function () {
          return deleteoperation(obj);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // console.log(this.cols);
      // return;
      this.downExport(
        "conf/bitableoperation/export?tableName=" + this.queryParams.tableName,
        { ...this.person },

        //   tableName
        // }
        // ...this.queryParams,
        // JSON.stringify(this.person),
        // },
        `export_${new Date().getTime()}.xlsx`
      );
    },

    //图片上传前的相关判断
    beforeAvatarUpload(file) {
      // const isJPG = file.type == 'image/jpeg' || file.type == 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 100;
      // if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error("上传导入文件大小不能超过 100MB!");
      }

      return isLt2M;
    },
    handleRemove(file, fileList) {
      if (!fileList.length) {
        this.hasFile = false;
      }
      this.dataForm.file = null;
    },
    handleChange(file, fileList) {
      if (fileList.length > 1) {
        this.dataForm.file = fileList.slice(-1);

        // this.fileList = [fileList[fileList.length - 1]]//这一步，是 展示最后一次选择文件
      }
      return;
      if (fileList.length >= 2) {
        return;
      }
      if (fileList.length === 1) {
        this.hasFile = true;
      }
      this.dataForm.file = file;
    },
    //确定按钮
    //调用组件upload的submit方法，从而触发httpRequest方法，实现手动上传
    submitUpload() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$refs.uploadImport.submit();
        }
      });
    },
    httpRequest(param) {
      // if (this.dataForm.name.length < 3) {
      //   this.$modal.msgWarning("请选择到店铺");
      //   return;
      // }
      let fd = new FormData();
      fd.append("file", param.file); // 传文件
      // let SysTableField;
      // SysTableField.setJSON(this.formData.libraryIdList);
      // fd.append('SysTableField',this.formData.libraryIdList);
      // let arr = this.formData.libraryIdList
      // console.log();
      // for (let i in this.formData.libraryIdList) {

      fd.append("isCheckDataNum", this.isCheckDataNum);
      fd.append("SysTableField", JSON.stringify(this.formData.libraryIdList));
      // }
      // fd.append("brand", this.dataForm.name[0]);
      // fd.append("channel", this.dataForm.name[1]);
      //dataPar.file.raw
      console.log(JSON.stringify(fd));
      this.openLoading();
      axios
        .post(
          process.env.VUE_APP_BASE_API +
            "/conf/bitableoperation/insertBatch?tableName=" +
            this.queryParams.tableName,
          fd,
          {
            headers: {
              header: { responseType: "blob" },

              Authorization: "Bearer " + getToken(),
              "Content-Type": "multipart/form-data",
            }, //定义内容格式,很重要
            // // timeout: 20000,
          }
        )
        .then((response) => {
          this.$refs.uploadImport.clearFiles(); //去掉文件列表
          this.$modal.closeLoading();
          console.log(response);
          if (response.data.code == 200) {
            this.dialogVisible = false;

            this.$modal.msgSuccess("导入成功");
            this.hasFile = false;
            this.getList();
            return;
            var apply = this.noticForm.noticConfig.map((item) => item.name[0]);
            if (!apply[0].comment) {
              this.noticForm.noticConfig = [];
              response.data.forEach((item) => {
                this.noticForm.noticConfig.push({
                  name: [{ ...item }],
                });
              });
            } else {
              response.data.forEach((item) => {
                this.noticForm.noticConfig.push({
                  name: [{ ...item }],
                });
              });
            }
          } else {
            this.hasFile = false;
            this.$modal.msgError("导入失败");
          }
        });
    },
    changecascadeList(value) {
      console.log(JSON.stringify(value));
    },
    //从表中选字段
    selectgetTablefieldsWithComments() {
      if (!this.queryParams.tableName) {
        return;
      }
      getTablefieldsWithComments({
        tableName: this.queryParams.tableName,
      }).then((response) => {
        this.tableNameList = [];
        this.tableNameList = response;
      });
    },
    //匹配
    changefieldName(item) {
      // console.log(JSON.stringify(item));
      // return;
      const selectedOption = this.tableNameList.find(
        (option) => option.field_name === item.field_name
      );
      console.log(JSON.stringify(selectedOption)); // 这里就是整个选项对象
      item.comment = selectedOption.comment;
      console.log(JSON.stringify(item));
    },
    //部门文件导入修改打开
    daoru() {
      this.formData.libraryIdList = [];
      this.selectgetTablefieldsWithComments();
      this.dialogVisible = true;
    },
    // 打开加载层
    openLoading() {
      this.$modal.loading("正在加载，请稍候！");
    },
    handleRuleTagger() {
      this.openLoading();
      RuleTagger({ tableName: this.queryParams.tableName }).then((response) => {
        this.$modal.closeLoading();
        if (response.code == 200) {
          this.$modal.msgSuccess("打标成功");
          this.getList();
        }
      });
    },
    handleBiTableRelation() {
      if (!this.queryParams.tableName) {
        return;
      }
      this.sqlTableName = this.queryParams.tableName;
      this.openBiTableRelation = true;
    },
    handleBiruletag() {
      if (!this.queryParams.tableName) {
        return;
      }
      this.sqlTableName = this.queryParams.tableName;
      this.openForBiruletag = true;
    },
    handleGo(path) {
      this.$router.push({
        path: path,
        query: { tableName: this.queryParams.tableName },
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.el-dialog-div {
  height: 60vh;
  overflow-x: hidden;
}
.el-dialog-divupload {
  height: 10vh;
  overflow-x: hidden;
}
</style>